{% extends "shuup/front/macros/theme/checkout.jinja" %}
{% from "shuup/front/macros/general.jinja" import render_field %}
{% from "shuup/front/macros/order.jinja" import render_lines_table, service_panel with context%}

{% macro buttons_container() %}
    <div class="clearfix">
        {{ caller() }}
    </div>
{% endmacro %}

{% macro next_button() %}
    <button type="submit" class="btn btn-primary btn-lg pull-right">
        <i class="fa fa-check"></i> {% trans %}Continue{% endtrans %}
    </button>
{% endmacro %}

{% macro default_buttons() %}
    {% call buttons_container() %}
        {{ next_button() }}
    {% endcall %}
{% endmacro %}

{% macro address_phase_billing_well(billing_form, company_form=None, saved_address_form=None) %}
    <div class="well">
        <fieldset>
            {% if saved_address_form and saved_address_form.fields.addresses.choices|count > 1 %}
                {{ render_address_form(None, saved_address_form, "saved_billing") }}
            {% endif %}

            {{ render_address_form(_("Billing address"), billing_form, "billing") }}
            {% if company_form %}
                {{ render_company_form(
                    _("Ordering for a company?"),
                    _("Please fill out these fields if you are ordering for a company."),
                    company_form.name, company_form.tax_number) }}
            {% endif %}
        </fieldset>
    </div>
{% endmacro %}

{% macro address_phase_shipping_well(shipping_form, ship_to_billing_checkbox=True, saved_address_form=None) %}
    <div class="well">
        <fieldset>
            {% if saved_address_form and saved_address_form.fields.addresses.choices|count > 1 %}
                {{ render_address_form(None, saved_address_form, "saved_shipping") }}
            {% endif %}
            {{ render_address_form(_("Shipping address"), shipping_form, "shipping", ship_to_billing_checkbox) }}
        </fieldset>
    </div>
{% endmacro %}

{% macro render_address_form(title, form, div_id, ship_to_billing_checkbox=False) %}
    {% if title %}
    <div class="row">
        <div class="order-for-company col-md-9 col-md-offset-3">
            <legend>{{ title }}</legend>
            {% if ship_to_billing_checkbox %}
                {{ ship_to_billing_address_checkbox() }}
            {% endif %}
        </div>
    </div>
    {% endif %}
    <div id="{{ div_id }}" class="form-horizontal">
        {% for field in form %}
            {{ render_field(field, layout="horizontal", show_help_text=False) }}
        {% endfor %}
    </div>
{% endmacro %}

{% macro ship_to_billing_address_checkbox() %}
    <div class="custom-checkbox">
        <input type="checkbox" name="same_as_billing" id="same_as_billing" value="1"{% if request.POST.get("same_as_billing", false) %} checked{% endif %}>
        <label for="same_as_billing">{% trans %}Ship to my billing address{% endtrans %}</label>
    </div>
    <hr>
{% endmacro %}

{% macro render_company_form(title, help_text, name_field, tax_number_field) %}
    {% if form %}
        <div class="row">
            <div class="order-for-company col-md-9 col-md-offset-3">
                <hr>
                <h4>{{ title }}</h4>
                <p>{{ help_text }}</p>
            </div>
        </div>
        <div class="form-horizontal">
            {{ render_field(name_field, layout="horizontal") }}
            {{ render_field(tax_number_field, layout="horizontal") }}
        </div>
    {% endif %}
{% endmacro %}

{% macro render_company_form_well(title, help_text, name_field, tax_number_field) %}
    <div class="well">
        <fieldset>
            <legend>{{ title }}</legend>
            <p>{{ help_text }}</p>
            <div class="row">
                <div class="col-sm-6">
                    {{ render_field(name_field) }}
                </div>
                <div class="col-sm-6">
                    {{ render_field(tax_number_field) }}
                </div>
            </div>
        </fieldset>
    </div>
{% endmacro %}

{% macro address_phase_extrajs() %}
    <script type="text/javascript">
        $(function(){
            var shouldCopyFields = false;

            function toggleAndCopyFields() {
                shouldCopyFields = $("#same_as_billing").is(":checked");

                if (shouldCopyFields) {
                    // copy all billing fields values to shipping fields
                    $("#billing :input").each(function (index, element) {
                        copyFieldValue(this);
                    });
                }

                $("#shipping :input")
                    .attr("readonly", shouldCopyFields)
                    .toggleClass("disabled", shouldCopyFields)
                    .trigger("change");

                // copy all billing fields values to shipping fields AGAIN
                // this is required when region app is enabled
                // as we can't guarantee the order fields are copied.
                // the region code could be copied before the country and when country
                // is changed, the region code field can be replaced by a select and
                // have options created. this way, we should copy values
                // before the `change` event trigged above and once again after
                // all fields get changed
                if (shouldCopyFields) {
                    $("#billing :input").each(function (index, element) {
                        copyFieldValue(this);
                    });
                }
            }

            function copyFieldValue(element) {
                if(!shouldCopyFields || !element)
                    return;
                var targetName = $(element).attr("id").split("-")[1];
                var $target = $("#id_shipping-" + targetName);
                $target.val(element.value);
                $target.trigger("change");
            }

            function activateCheckoutAddressCopy() {
                $("#id_shipping-country").attr("readonly", true);
                toggleAndCopyFields();
                $("#billing :input").on("input change", function (evt) {
                    copyFieldValue(evt.target);
                });
                $("#same_as_billing").on("change", toggleAndCopyFields);
            }
            activateCheckoutAddressCopy();

            // we detectec that a field could be replaced by any other input
            // in cases like regions module is injected
            // this way, we must attach the event again
            document.addEventListener("regionFieldInitialized", function (evt) {
                if ($(evt.detail.field).attr("name").indexOf("billing") >= 0) {
                    $(evt.detail.field).on("input change", function (evt) {
                        copyFieldValue(evt.target)
                    });
                }
            });

            function copyFromSavedAddresses(targetInputs, savedAddress) {
                $(targetInputs).each(function() {
                    var fieldName = $(this).attr("id").split("-")[1];
                    var value = savedAddress[fieldName];
                    $(this).toggleClass("disabled", value ? true : false);
                    $(this).val(value);
                });
            }

            $("#id_saved_billing-addresses").on("change", function(){
                var savedAddressId = $(this).val();
                if (!savedAddressId) {
                    $("#billing :input").toggleClass("disabled", false)
                    return;
                }
                copyFromSavedAddresses("#billing :input", window.SAVED_ADDRESSES[savedAddressId]);
                $("#billing :input").trigger("change");
                copyFromSavedAddresses("#billing :input", window.SAVED_ADDRESSES[savedAddressId]);
            });

            $("#id_saved_shipping-addresses").on("change", function(){
                var savedAddressId = $(this).val();
                $("#shipping :input").attr("readonly", false).toggleClass("disabled", false);

                if (!savedAddressId) {
                    // enable same as billing
                    $("#same_as_billing").attr("disabled", false);
                    return;
                }
                copyFromSavedAddresses("#shipping :input", window.SAVED_ADDRESSES[savedAddressId]);
                $("#shipping :input").trigger("change");
                copyFromSavedAddresses("#shipping :input", window.SAVED_ADDRESSES[savedAddressId]);

                // disable same as billing
                $("#same_as_billing").prop("checked", false);
                $("#same_as_billing").attr("disabled", true);
            });
        });

        window.SAVED_ADDRESSES = {{ saved_address|json if saved_address else "{}"|safe }};
    </script>
{% endmacro %}

{% macro method_phase_shipping_panel(form) %}
    {{ method_phase_service_panel(_("Choose Shipping Method"), form.shipping_method, form.fields["shipping_method"].choices|length) }}
{% endmacro %}

{% macro method_phase_payment_panel(form) %}
    {{ method_phase_service_panel(_("Choose Payment Method"), form.payment_method, form.fields["payment_method"].choices|length) }}
{% endmacro %}

{% macro method_phase_service_panel(panel_title, field, has_options=true) %}
    <div class="panel panel-default">
        <div class="panel-heading">
            <h2 class="panel-title">{{ panel_title }}</h2>
        </div>
        <div class="panel-body">
            {% if has_options %}
                {{ field }}
            {% else %}
                <div class="text-center">{{ _("No method is available.") }}</div>
            {% endif %}
        </div>
    </div>
{% endmacro %}

{% macro confirm_phase_order_information(basket) %}
    <div class="well">
        {% set lines = basket.get_final_lines() %}
        {{ render_lines_table(
            lines, basket.taxful_total_price, basket.taxless_total_price, show_product_package_info=True) }}
    </div>
{% endmacro %}

{% macro render_shipping_address(basket, column_class="col-sm-6") %}
    <div class="{{ column_class }}">
        {{ service_panel(_("Delivery"), _("Delivery method"), _("Shipping address"), basket.shipping_method, basket.shipping_address) }}
    </div>
{% endmacro %}

{% macro render_billing_address(basket, column_class="col-sm-6") %}
    <div class="{{ column_class }}">
        {{ service_panel(_("Billing"), _("Payment method"), _("Billing address"), basket.payment_method, basket.billing_address) }}
    </div>
{% endmacro %}

{% macro confirm_phase_address_information(basket) %}
    <div class="row">
        {% if basket.shipping_address and basket.billing_address %}
            {{ render_shipping_address(basket) }}
            {{ render_billing_address(basket) }}
        {% elif basket.billing_address %}
            {{ render_billing_address(basket, "col-sm-12") }}
        {% elif basket.shipping_address %}
            {{ render_shipping_address(basket, "col-sm-12") }}
        {% endif %}
    </div>
{% endmacro %}

{% macro render_confirm_form(form) %}
    <form role="form" method="post" action="{{ phase_urls["confirm"] }}" id="confirm_form">
        {% csrf_token %}
        <div class="panel panel-default">
            <div class="panel-heading">
                <h2 class="panel-title">
                    {% trans %}Add comment{% endtrans %}
                </h2>
            </div>
            <div class="panel-body">
                {{ render_field(form.comment) }}
            </div>
        </div>
        <hr>
        <input type="hidden" name="product_ids" value="{{ product_ids }}" />
        {% if form.marketing %}
            {{ render_field(form.marketing) }}
        {% endif %}
        {% for field in form %}
            {% if field.name.startswith("accept_") %}
                {{ render_field(field) }}
            {% endif %}
        {% endfor %}
        <hr>
        {{ place_order_button() }}
    </form>
{% endmacro %}

{% macro render_confirm_form_single_page(form) %}
    <div class="row">
        <div class="col-sm-12">
            <div class="well">
                <fieldset>
                    <legend>{% trans %}Other information{% endtrans %}</legend>
                    <div class="row">
                        <div class="col-sm-6">
                            {{ render_field(form.shipping_method) }}
                        </div>
                        <div class="col-sm-6">
                            {{ render_field(form.payment_method) }}
                        </div>
                    </div>
                    <div class="row" id="shipping-options-container">
                        {{ shipping_method_ui_html|default("")|safe }}
                    </div>
                    <div class="row">
                        <div class="col-sm-12">
                            {{ render_field(form.comment) }}
                        </div>
                    </div>
                </fieldset>
            </div>
        </div>
    </div>
    <hr>
    {{ render_field(form.accept_terms) }}
    {{ place_order_button() }}
{% endmacro %}

{% macro place_order_button() %}
    <button type="submit" class="btn btn-primary btn-lg">
        <i class="fa fa-check"></i> {% trans %}Place Order{% endtrans %}
    </button>
{% endmacro %}

